import React from 'react';
import s from './style.module.css';
import cn from 'classnames';
import Breadcrumb, { Item } from '../../../../../components/Breadcrumb';
import Label from '../../../../../components/Label';
import Anchor from '@knownsec/react-component/dist/Anchor';
import { withRouter } from 'react-router';
import PropTypes from 'prop-types';
import { datetime } from '../../../../../../common/formatter';

const { Link } = Anchor;

function VulDetail({ location }) {
	let locationInfo = {};
	if (location?.state) {
		sessionStorage.setItem('locationState', JSON.stringify(location.state));
		locationInfo = location?.state;
	} else {
		const state = JSON.parse(sessionStorage.locationState);
		locationInfo = state;
	}
	const { row, assetType, jid, atid, tid } = locationInfo;
	const handleAnchorClick = e => {
		e.preventDefault();
	};
	const cJoin = e => {
		if (e) {
			return e.length > 0 ? e.join('｜') : '- -';
		} else {
			return '- -';
		}
	};
	const bread = () => {
		if (location.pathname.includes('/asset-manage/manage')) {
			return (
				<Breadcrumb>
					<Item disabled key="asset-manage">
						资产管理
					</Item>
					<Item key="manage/host">主机资产</Item>
					<Item key="Detail">详情</Item>
					<Item>漏洞详情</Item>
				</Breadcrumb>
			);
		} else {
			return (
				<Breadcrumb>
					<Item disabled key="job-manage">
						任务管理
					</Item>
					<Item key={`host-task`}>主机安全监测</Item>
					<Item key={`detail?jid=${jid}&tid=${tid}&id=${atid}`}>监测结果</Item>
					<Item>漏洞详情</Item>
				</Breadcrumb>
			);
		}
	};
	const base64Decode = input => {
		if (input) {
			try {
				let rv = window.atob(input);
				rv = escape(rv);
				rv = decodeURIComponent(rv);
				return rv;
			} catch (error) {
				console.log(error);
				return '';
			}
		} else {
			return '';
		}
	};
	const formatData = (row, key) => {
		let traffics = {};
		const length = row?.traffics?.length;
		for (let index = length - 1; index >= 0; index--) {
			const item = row?.traffics[index] || {};
			if (
				JSON.stringify(item.request) !== '{}' &&
				JSON.stringify(item.response) !== '{}'
			) {
				traffics = item;
				break;
			}
		}

		if (traffics.type_name === 'tcp') {
			const vulBp = {
				请求内容: '暂无数据',
				响应内容: '暂无数据',
				Payload: '暂无数据',
				漏洞详情: row?.detailText,
				漏洞影响: row?.impact,
				漏洞概述: row?.description,
				修复建议: row?.recommendation,
				参考信息: row?.reference[0],
			};
			return vulBp[key];
		} else {
			let url = '/';
			if (traffics?.request?.url) {
				let url_ = traffics?.request?.url.replace('//', '/').split('/');
				url_.splice(0, 2);
				url_ = url_.join('/');
				url = '/' + url_;
			}

			let request = JSON.stringify(traffics?.request?.headers || {})
				.replace(/^\{(.*)\}$/g, '$1')
				.replace(/,"/g, ',')
				.replace(/":/g, ': ')
				.replace(/",/g, '"\n')
				.replace(/"/g, '');
			if (traffics?.request?.method && traffics?.response?.version) {
				request =
					`${traffics?.request?.method} ${url} ${traffics?.response?.version}\n` +
					request;
			}
			request = request.replace(/",/g, '"\n');
			request.includes('undefined') && (request = '暂无数据');
			request = `${request && request + '\n\n'}${base64Decode(
				traffics?.request?.b64content
			)}`;
			const { headers } = traffics?.response || {};
			let response = JSON.stringify(headers || {})
				.replace(/^\{(.*)\}$/g, '$1')
				.replace(/,"/g, ',')
				.replace(/":/g, ': ');

			if (traffics?.response?.version && traffics?.response?.status_code) {
				response =
					`${traffics?.response?.version} ${traffics?.response?.status_code}\n` +
					response;
			}
			response = response.replace(/",/g, '"\n').replace(/"/g, '');
			response = `${response && response + '\n\n'}${base64Decode(
				traffics?.response?.b64content
			)}`;
			response.includes('undefined') && (response = '暂无数据');
			const vulBp = {
				请求内容: request || '暂无数据',
				响应内容: response || '暂无数据',
				Payload: row?.payload || '暂无数据',
				漏洞详情: row?.detailText,
				漏洞影响: row?.impact,
				漏洞概述: row?.description,
				修复建议: row?.recommendation,
				参考信息: row?.reference[0],
			};
			return vulBp[key];
		}
	};
	return (
		<div className={s.vulDetail}>
			<div className={s.breadcrumb}>{bread()}</div>
			<div className={s.container}>
				<div>
					<div className={s.header}>
						<Label className={cn(s.mb10, s.mt20)}>漏洞详情</Label>
					</div>
					<div className={cn(s.df, s.aic, s.p0_10)}>
						<span className={cn(s.flex1, 'ell')} title={row.vuln_name}>
							漏洞名称：{row.vuln_name}
						</span>
						<span className={cn(s.flex1, 'ell')} title={row.vuln_type}>
							漏洞类型：{row.vuln_type}
						</span>
						<span className={cn(s.flex1, 'ell')} title={row.level_name}>
							威胁等级：{row.level_name}
						</span>
					</div>
					<div className={cn(s.df, s.aic, s.p0_10, s.mt10)}>
						<span className={s.flex1}>
							发现时间：{datetime(row.found_at) || '暂无'}
						</span>
						<span className={s.flex1}>CVE编号：{cJoin(row.cve)}</span>
						<span className={s.flex1}>CNNVD编号：{cJoin(row.cnnvd)}</span>
					</div>
				</div>
				<div className={cn(s.df, s.aifs, s.pr, s.mt24, s.flex1, s.vdBox)}>
					<Anchor
						className={s.anchoritem}
						onClick={handleAnchorClick}
						getContainer={() => document.getElementById('vd')}
					>
						<Link href="#query-content" title="请求内容" />
						<Link href="#response-content" title="响应内容" />
						<Link href="#payload" title="Payload" />
						<Link href="#vul-detail" title="漏洞详情" />
						<Link href="#vul-effect" title="漏洞影响" />
						<Link href="#vul-summary" title="漏洞概述" />
						<Link href="#repair-suggestions" title="修复建议" />
						<Link href="#reference-information" title="参考信息" />
					</Anchor>
					<div id="vd" className={cn(s.vd, s.p0_10)}>
						<div id="query-content">
							<Label className={cn(s.mb10, s.mt20)}>请求内容</Label>
							{formatData(row, '请求内容') === '暂无数据' ? (
								<div className={s.p0_5}>暂无数据</div>
							) : (
								<pre className={s.p0_5}>{formatData(row, '请求内容')}</pre>
							)}
						</div>
						<div id="response-content">
							<Label className={cn(s.mb10, s.mt20)}>响应内容</Label>
							{formatData(row, '响应内容') === '暂无数据' ? (
								<div className={s.p0_5}>暂无数据</div>
							) : (
								<pre className={s.p0_5}>{formatData(row, '响应内容')}</pre>
							)}
						</div>
						<div id="payload">
							<Label className={cn(s.mb10, s.mt20)}>Payload</Label>
							{formatData(row, 'Payload') === '暂无数据' ? (
								<div className={s.p0_5}>暂无数据</div>
							) : (
								<pre className={s.p0_5}>{formatData(row, 'Payload')}</pre>
							)}
						</div>
						<div id="vul-detail">
							<Label className={cn(s.mb10, s.mt20)}>漏洞详情</Label>
							<div className={s.p0_5}>{row.detail || '暂无数据'}</div>
						</div>
						<div id="vul-effec">
							<Label className={cn(s.mb10, s.mt20)}>漏洞影响</Label>
							<div className={s.p0_5}>{row.impact || '暂无数据'}</div>
						</div>
						<div id="vul-summary">
							<Label className={cn(s.mb10, s.mt20)}>漏洞概述</Label>
							<div className={s.p0_5}>{row.description || '暂无数据'}</div>
						</div>
						<div id="repair-suggestions">
							<Label className={cn(s.mb10, s.mt20)}>修复建议</Label>
							<div className={s.p0_5}>{row.recommendation || '暂无数据'}</div>
						</div>
						<div id="reference-information">
							<Label className={cn(s.mb10, s.mt20)}>参考信息</Label>
							<div className={s.p0_5}>{row.reference[0] || '暂无数据'}</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	);
}
VulDetail.propTypes = {
	location: PropTypes.any,
};
export default withRouter(VulDetail);
